﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

using BodaNetCommunications.CommBase.Interfaces;
using BodaNetCommunications.Utilities.ComTypes;

namespace BodaNetCommunications.McComs
{
    [McPlc(McPLCType.Keyence_KV7500)]
    public class KeyenceKV7500AddressTransfer : IAddressTransfer
    {
        // 增加缓存
        static Dictionary<string, (McAddressArea, string)> _dicts = new Dictionary<string, (McAddressArea, string)>();
        private static object _lock = new object();
        public (McAddressArea, string) TransferAddress(string address)
        {
            if (_dicts.Keys.Contains(address)) return _dicts[address];

            var areaType = typeof(KeyenceAddressArea);
            if (false == areaType.IsEnum) throw new Exception($"未获取到{nameof(McPLCType.Keyence_KV7500)}的地址枚举类型");
            // 获取两个字符长度的枚举值名称
            string[] twoLettersEnumNames = Enum.GetNames(areaType).Where(m => m.Length == 2).ToArray();

            string area = address.Substring(0, 2).ToUpperInvariant();
            if (!twoLettersEnumNames.Contains(area))
            {
                area = address.Substring(0, 1).ToUpperInvariant();
            }

            KeyenceAddressArea eAddrArea = Enum.TryParse<KeyenceAddressArea>(area, out var areaTemp) ? areaTemp : throw new Exception($"无法将地址[address]转换为基恩士的数据区域名称");
            McAddressArea mcAddressArea = eAddrArea.GetType().GetCustomAttribute<McAddressAttribute>().McAddressArea;

            string startAddress = address.Substring(area.Length);
            // TODO: 地址根据PLC类型去转换

            lock (_lock)
            {
                if (!_dicts.Keys.Contains(address))
                    _dicts.Add(address, (mcAddressArea, startAddress));
            }

            return (mcAddressArea, startAddress);
        }
    }
}